import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Input,
  Button,
  Table,
  Card,
  message,
  Icon,
  Pagination,
  Radio,
  Form,
  Modal,
  Spin,
  Switch
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { FormattedMessage } from 'umi-plugin-react/locale';
import moment from 'moment';
const confirm = Modal.confirm;
import PageLoading from '@/components/PageLoading';
import styles from './index.less';

const Search = Input.Search;
const CollectionCreateForm = Form.create({ name: 'form_in_modal' })(
  class extends React.Component {

    checkField(rule, value, callback){
      var reg =/^[0-9a-zA-Z_]{1,}$/g;
      if(rule.field === 'mail'){
        if(value){
          if(reg.test(value))
          {
            if(value.length>20 || value.length<6){
              callback('支持6-20位大小写字母、数字和下划线')
            }else{
              callback()
            }
          }else{
            callback('支持6-20位大小写字母、数字和下划线')
          }
        }else{
          callback('')
        }
      }else{
        if(value){
          callback()
        }else{
          callback('')
        }
      }

    };



    render() {
      const { visible, onCancel, onCreate, form, userInfo, isEdit, loading } = this.props;
      const { getFieldDecorator } = form;
      const formItemLayout = {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 },
        },
      };
      return (
        <Modal
          visible={visible}
          title="添加编辑角色"
          okText="保存"
          onCancel={onCancel}
          onOk={onCreate}
        >
          <Spin spinning={loading}>
            <Form {...formItemLayout}>
              {isEdit ? (
                <Form.Item label="角色名称">
                  {getFieldDecorator('roleName', {
                    validateTrigger: ['onChange', 'onBlur'],
                    initialValue: userInfo.roleName,
                    rules: [{ required: true, message: '请输入角色名称' },{
                      validator: this.checkField,
                    }],
                  })(<Input placeholder="请输入角色名称" />)}
                </Form.Item>
              ) : (
                <Form.Item label="角色名称">
                  {getFieldDecorator('roleName', {
                    validateTrigger: ['onChange', 'onBlur'],
                    rules: [{ required: true, message: '请输入角色名称' },{
                      validator: this.checkField,
                    }],
                  })(<Input placeholder="请输入角色名称" />)}
                </Form.Item>
              )}
              <Form.Item label="状态">
                {getFieldDecorator('userStatus',{
                  valuePropName: 'checked',
                  initialValue: userInfo.userStatus === '0' ? true:false
                })(
                  <Switch
                    checkedChildren="启用"
                    unCheckedChildren="停用"
                  />
                )}
              </Form.Item>
              {isEdit ? (
                <Form.Item label="描述">
                  {getFieldDecorator('remakers', {
                    initialValue: userInfo.remakers,
                    rules: [{ required: false, message: '描述' }],
                  })(<Input placeholder="角色的描述" />)}
                </Form.Item>
              ) : (
                <Form.Item label="描述">
                  {getFieldDecorator('remakers', {
                    rules: [{ required: false, message: '描述' }],
                  })(<Input placeholder="角色的描述" />)}
                </Form.Item>
              )}
            </Form>
          </Spin>
        </Modal>
      );
    }
  }
);

@connect(({ roleManagement, loading }) => ({
  roleManagement,
  loading: loading.effects['roleManagement/getUsers'],
}))
class Roles extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      notices: [],
      tableLoading: true,
      total: 0,
      visible: false,
      searchText: '',
      userInfo: {},
      isEdit: false,
      loading: true,
      pageSize: 10,
      auth: true,
      jy: false,
    };
    this.columns = [
      {
        key: 'roleName',
        align: 'left',
        title: '角色名称',
        dataIndex: 'roleName',
      },
      {
        key: 'userStatus',
        align: 'left',
        title: '状态',
        dataIndex: 'userStatus',
        render: dataIndex => {
          return (
            <div>
              {
                dataIndex ==='0'?'启用':'停用'
              }
            </div>
          )
        },
      },
      {
        key: 'remakers',
        align: 'left',
        title: '备注',
        dataIndex: 'remakers',
      },
      // {
      //   key: 'rolesDes',
      //   align: 'left',
      //   title: '用户角色',
      //   dataIndex: 'rolesDes',
      // },
      // {
      //   key: 'departmentName',
      //   align: 'left',
      //   title: '所属业务',
      //   dataIndex: 'departmentName',
      // },
      {
        key: 'updateTime',
        align: 'left',
        title: '创建时间',
        dataIndex: 'updateTime',
        // render: dataIndex => {
        //   return moment(parseInt(dataIndex)).format('YYYY-MM-DD HH:mm:ss');
        // },
      },
      {
        title: '操作',
        align: 'left',
        render: (text, row) => {
          return (
            <div>
               <Button type="primary" icon="edit" htmlType='button' size='small' style={{marginRight:5}} onClick={() => this.queryUser(row)}>
              编辑
            </Button>
              {
                row.userStatus==='0'? <Button
                  type="danger"
                  icon="pause"
                  htmlType="button"
                  size="small"
                  style={this.qwe(row)}
                  onClick={() => this.fixRoleStatus(1,row)}
                >
                  停用
                </Button>:
                  <Button
                    icon="caret-right"
                    htmlType="button"
                    size="small"
                    style={this.qwe(row)}
                    onClick={() => this.fixRoleStatus(0,row)}
                  >
                    启用
                  </Button>
              }
              <Button
                disabled={this.todo(row)}
                type="danger"
                icon="close"
                htmlType="button"
                size="small"
                style={this.qwe(row)}
                onClick={() => this.showDeleteConfirm(row)}
              >
                删除
              </Button>
            </div>
          );
        },
        width: '300px',
      },
    ];
  }

  componentDidMount() {
    this.getUsers();
  }

  showModal = () => {
    const form = this.formRef.props.form;
    form.resetFields();
    this.setState({ visible: true, loading: false, userInfo: {} });
  };

  handleCancel = () => {
    const form = this.formRef.props.form;
    form.resetFields();
    this.setState({ visible: false, isEdit: false });
  };

  handleCreate = () => {
    const form = this.formRef.props.form;
    const type = this.state.isEdit;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      if (type) {
        this.editUser(values);
      } else {
        this.addUser(values);
      }
      form.resetFields();
      this.setState({ visible: false });
    });
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };

  onChangeForPage = number => {
    this.setState(
      {
        page: number,
        tableLoading: true,
      },
      () => {
        this.getUsers();
      }
    );
  };

  fixRoleStatus = (status,row) =>{
    const { dispatch } = this.props;
    dispatch({
      type: 'roleManagement/updateRoles',
      payload: { userStatus: status,roleId:row.roleId},
      callback: res => {
        if (!res.code) {
          message.info(res.msg);
          this.getUsers();
        } else {
          this.setState({
            auth: false,
          });
        }
      },
    });
  };

  onShowSizeChangeForPage = (current, size) => {
    this.setState(
      {
        page: current,
        pageSize: size,
        tableLoading: true,
      },
      () => {
        this.getUsers();
      }
    );
  };

  getUsers = () => {
    const { dispatch,currentUser } = this.props;
    const {page,pageSize,searchText} = this.state;
    dispatch({
      type: 'roleManagement/getRoleLists',
      payload: { createUserId:currentUser.uid,page,rows:pageSize,roleName:searchText },
      callback: res => {

        this.setState({
          notices: res.list,
          total: parseInt(res.total),
          tableLoading: false,
        });
      },
    });
  };

  addUser = obj => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'roleManagement/addRoles',
      payload: { roleName: obj.roleName, remakers: obj.roleName, userStatus: obj.userStatus?0:1,userId:currentUser.uid },
      callback: res => {
        if(!res.code){
          this.getUsers();
          message.info('添加成功')
        }
      },
    });
  };

  delUser = row => {
    const { dispatch } = this.props;
    dispatch({
      type: 'roleManagement/delRoles',
      payload: { roleId: row.roleId },
      callback: res => {
        if(!res.code){
            message.info('执行成功');
            return this.getUsers();
        }
      }
    });
  };

  showDeleteConfirm = row => {
    const that = this;
    confirm({
      title: '确认删除【' + row.roleName + '】该角色么',
      content: '',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        that.delUser(row);
      },
      onCancel() {

      },
    });
  };

  resetUser = row => {
    const { dispatch } = this.props;
    dispatch({
      type: 'roleManagement/resetUser',
      payload: { userId: row._id },
      callback: res => {
        if (res.status) {
          return message.info(res.msg);
        }
        return message.error(res.msg);
      },
    });
  };

  editUser = row => {
    const { dispatch, currentUser } = this.props;
    const { userInfo } = this.state;
    dispatch({
      type: 'roleManagement/updateRoles',
      payload: { roleName: row.roleName, remakers: row.remakers, userStatus: row.userStatus?0:1,roleId:userInfo.roleId},
      callback: res => {
        if (!res.code) {
          message.info(res.msg);
          this.getUsers();
        } else {
          this.setState({
            auth: false,
          });
        }
      },
    });
  };

  queryUser = row => {
    const { dispatch } = this.props;
    this.setState({ visible: true, isEdit: true, loading: true });
    dispatch({
      type: 'roleManagement/getRoleByRoleIds',
      payload: { roleId: row.roleId },
      callback: res => {
        this.setState({ userInfo: res, loading: false });
      },
    });
  };

  setSearch = val => {
    this.setState(
      {
        searchText: val,
      },
      () => {
        this.getUsers();
      }
    );
  };

  setClassName = (record, index) => {
    const { currentUser } = this.props;
    if (currentUser.nick === record.nick) {
      return styles.red;
    } else {
      // this.setState({jy:false})
    }
  };

  todo = row => {
    const { currentUser } = this.props;
    if (currentUser.nick === row.nick) {
      return true;
    }
  };

  sty = row => {
    const { currentUser } = this.props;
    if (currentUser.nick === row.nick) {
      return { marginRight: 5 };
    } else {
      return { marginRight: 5, backgroundColor: 'orange', color: '#fff' };
    }
  };

  qwe = row => {
    const { currentUser } = this.props;
    if (currentUser.nick === row.nick) {
      return { marginRight: 5 };
    } else {
      return { marginRight: 5,  };
    }
  };

  render() {
    const { notices, tableLoading, page, total, pageSize, userInfo, isEdit, loading } = this.state;
    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <Card bordered={false}>
            <div
              style={{ marginBottom: 10, borderBottom: '1px solid lightgrey', paddingBottom: 10 }}
            >
              <span
                style={{
                  fontSize: 16,
                  color: '#000',
                  borderLeft: '5px solid #13c2f3',
                  paddingLeft: 10,
                }}
              >
                角色管理
              </span>
            </div>
            <Row style={{ marginBottom: 10 }}>
              <Col span={4}>
                <Button
                  type="primary"
                  icon="plus"
                  htmlType="button"
                  style={{ marginRight: 5 }}
                  onClick={this.showModal}
                >
                  添加
                </Button>
              </Col>
              <Col offset={16} span={4}>
                <Search placeholder="请输入账户名" onSearch={value => this.setSearch(value)} />
              </Col>
            </Row>
            <div>
              <Table
                // rowClassName={this.setClassName}
                columns={this.columns}
                dataSource={notices}
                rowKey="roleId"
                pagination={{
                  // 分页
                  total,
                  pageSize, // 显示几条一页
                  defaultPageSize: page, // 当前页
                  showSizeChanger: true, // 是否显示可以设置几条一页的选项
                  showQuickJumper: true,
                  onChange: this.onChangeForPage,
                  onShowSizeChange: this.onShowSizeChangeForPage,
                }}
                loading={tableLoading}
              />
            </div>

            <CollectionCreateForm
              wrappedComponentRef={this.saveFormRef}
              visible={this.state.visible}
              onCancel={this.handleCancel}
              onCreate={this.handleCreate}
              userInfo={userInfo}
              isEdit={isEdit}
              loading={loading}
            />
          </Card>
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Roles);
